package com.phpxiu.app.view;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.config.Config;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.Permission;
import com.phpxiu.app.model.UploadResultInfo;
import com.phpxiu.app.model.card.RoomCardInfo;
import com.phpxiu.app.model.event.UserEditEvent;
import com.phpxiu.app.model.list.LoveState;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.viewinterface.UploadView;
import com.phpxiu.app.supports.selector.OptionsPopupWindow;
import com.phpxiu.app.supports.selector.TimePopupWindow;
import com.phpxiu.app.supports.selector.WheelItem;
import com.phpxiu.app.upload.TUploadHelper;
import com.phpxiu.app.utils.FileManager;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.dialog.DatePicker;
import com.phpxiu.app.view.dialog.PhotoOptionMenus;
import com.phpxiu.app.view.dialog.SexMenus;
import com.phpxiu.app.view.popupwindow.LoveStateSelector;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import de.greenrobot.event.EventBus;


/**
 * Created by WuJinZhou on 2016/6/2.
 */
public class UserInfoEdit extends UIBase implements View.OnClickListener,UploadView,SexMenus.OnSexSelectedCallback{
    public final static String TAG="UserInfoEdit";
    public final static String EXTRA_PARAM_USER_KEY="extra_param_user";
    private final static int REQUEST_CODE_EDIT_NICK=0x1;//编辑昵称请求
    private final static int  REQUEST_CODE_EDIT_INTRO=0x2;//编辑个性签名
    private final static int REQUEST_CODE_EDIT_JOB=0x3;//编辑职业信息
    private final static int REQUEST_CODE_EDIT_LOCATION=0x4;//编辑职业信息
    private WindowLayout mainView;
    private int mScreenWidth;
    private RoomCardInfo mUser;
    private DatePicker pwTime;
    private OptionsPopupWindow popupWindowAddress;
    private ArrayList<WheelItem> provinceItems=new ArrayList<WheelItem>();
    private ArrayList<ArrayList<WheelItem>> cityItems=new ArrayList<ArrayList<WheelItem>>();
    private TextView nameTv,birthTv,addrTv,introTv;
    private ImageView sexView;
    private SexMenus sexMenus;
    private TextView loveView;
    private TextView jobView;
    private FrescoImageView avatarView;
    private Uri localAvatar=null;
    private PhotoOptionMenus photoMenus;
    private RelativeLayout loadingBox;
    private ImageView loadingImage;
    private AnimationDrawable uploadAni;
    private ClipboardManager myClipboard;
    private ClipData myClip;
    private LoveStateSelector loveStateSelector;
    private TUploadHelper uploader;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uploader=new TUploadHelper(this,this,"avatar");
        myClipboard=(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
        mScreenWidth=(int) KKYApp.getInstance().screenWidth;
        mUser=(RoomCardInfo)getIntent().getSerializableExtra(EXTRA_PARAM_USER_KEY);
        if(mUser==null){
            finish();
            return;
        }
        setContentView(R.layout.user_info_edit);
        init();
    }

    public void init(){
        mainView=(WindowLayout)findViewById(R.id.user_info_edit_main_layout);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        findViewById(R.id.nick_link).setOnClickListener(this);
        avatarView=(FrescoImageView)findViewById(R.id.user_head_view);
        avatarView.setOnClickListener(this);
        avatarView.setImageURI(Uri.parse(mUser.getAvatar()));
        nameTv=(TextView)findViewById(R.id.nick_view);
        nameTv.setText(mUser.getNickname());
        findViewById(R.id.sex_link).setOnClickListener(this);
        sexView=(ImageView)findViewById(R.id.sex_icon_view);
        String sex=mUser.getSex();
        if("1".equals(sex)){
            sexView.setImageResource(R.mipmap.user_sex_icon_male);
        }else{
            sexView.setImageResource(R.mipmap.user_sex_icon_female);
        }
        findViewById(R.id.intro_link).setOnClickListener(this);
        introTv=(TextView)findViewById(R.id.intro_view);
        introTv.setText(mUser.getIntro());
        TextView liveNo=(TextView)findViewById(R.id.live_no_view);
        liveNo.setText(mUser.getUid());
        findViewById(R.id.live_no_link).setOnClickListener(this);
        findViewById(R.id.birth_link).setOnClickListener(this);
        birthTv=(TextView)findViewById(R.id.birth_view);
        birthTv.setText(mUser.getBirthday());
        findViewById(R.id.love_link).setOnClickListener(this);
        loveView=(TextView)findViewById(R.id.love_view);
        for (LoveState state: KKYApp.STATES){
            if(mUser.getMerrage().equals(state.getId())){
                loveView.setText(state.getTitle());
                break;
            }
        }
        findViewById(R.id.address_link).setOnClickListener(this);
        addrTv=(TextView)findViewById(R.id.address_view);
        addrTv.setText(mUser.getAddress());
        findViewById(R.id.job_link).setOnClickListener(this);
        jobView=(TextView)findViewById(R.id.job_view);
        jobView.setText(mUser.getJob());
        loadingBox=(RelativeLayout)findViewById(R.id.loading_box);
        loadingImage=(ImageView)findViewById(R.id.loading_header_view);
        uploadAni=(AnimationDrawable)loadingImage.getBackground();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.user_head_view:
                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
                    requestMyPermissions(Permission.REQUEST_PHOTO);
                }else {
                    editAvatar();
                }
                break;
            case R.id.nick_link:
                Intent editNick=new Intent(this,UserInfoNickEdit.class);
                editNick.putExtra(UserInfoNickEdit.EXTRA_PARAM_USER_NICK,mUser.getNickname());
                startActivityForResult(editNick,REQUEST_CODE_EDIT_NICK);
                break;
            case R.id.sex_link:
                editSex();
                break;
            case R.id.intro_link:
                Intent editIntro=new Intent(this,UserInfoIntroEdit.class);
                editIntro.putExtra(UserInfoIntroEdit.EXTRA_PARAM_INTRO_KEY,mUser.getIntro());
                startActivityForResult(editIntro,REQUEST_CODE_EDIT_INTRO);
                break;
            case R.id.live_no_link:
                myClip = ClipData.newPlainText("text", mUser.getUid());//设置剪贴板内容
                myClipboard.setPrimaryClip(myClip);//设置剪贴板内容
                mainView.showTopMsg(getString(R.string.id_copied_msg));
                break;
            case R.id.love_link:
                if(loveStateSelector==null){
                    loveStateSelector=new LoveStateSelector(this);
                }
                String state=mUser.getMerrage();
                if(state==null||"".equals(state)){
                    state="1";
                }
                loveStateSelector.show(state,getWindow().getDecorView());
                break;
            case R.id.birth_link:
                showDatePicker();
                break;
            case R.id.address_link:
                Intent lc=new Intent(this,UserInfoEditLocation.class);
                lc.putExtra(UserInfoEditLocation.EXTRA_PARAM_USER_LC,mUser.getAddress());
                startActivityForResult(lc,REQUEST_CODE_EDIT_LOCATION);
                //showZonePop();
                break;
            case R.id.job_link:
                Intent editJob=new Intent(this,UserInfoJobEdit.class);
                editJob.putExtra(UserInfoJobEdit.EXTRA_PARAM_USER_JOB,mUser.getJob());
                startActivityForResult(editJob,REQUEST_CODE_EDIT_JOB);
                break;
            default:
                break;
        }
    }

    /**
     * 编辑性别
     */
    private void editSex(){
        if(sexMenus==null){
            sexMenus=new SexMenus(this);
            sexMenus.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
            sexMenus.setCallback(this);
        }
        sexMenus.show();
    }

    /**
     * 性别选中回调
     * @param sex
     */
    @Override
    public void onSexSelected(final String sex) {
        if("1".equals(sex)){
            sexView.setImageResource(R.mipmap.user_sex_icon_male);
        }else{
            sexView.setImageResource(R.mipmap.user_sex_icon_female);
        }
        OKHttpParam param=OKHttpParam.builder(false);
        param.remove("platform");
        param.put("sex",sex);
        OKHttp.post(HttpConfig.API_UPDATE_USER_FIELD, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                KKYUtil.log(TAG, "修改性别结果：");
                MySelfInfo.getInstance().updateCacheString(UserInfoEdit.this, Constants.USER_SEX, sex);
                mUser.setSex(sex);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_SEX, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }

            @Override
            public void onErr(String errMsg) {
                resetSex();
                mainView.showTopMsg(errMsg);
            }

        });
    }

    /**
     * 修改性别失败
     */
    private void resetSex(){
        String sex=mUser.getSex();
        if("1".equals(sex)){
            mUser.setSex("0");
            sexView.setImageResource(R.mipmap.user_sex_icon_female);
        }else{
            mUser.setSex("1");
            sexView.setImageResource(R.mipmap.user_sex_icon_male);
        }
    }

    /**
     * 保存情感状态
     */
    public void onLoveStateItemClick(final LoveState state) {
        KKYUtil.log(TAG, "点击了感情项：" + state.getTitle() + "@" + state.getId());
        loveView.setText(state.getTitle());
        OKHttpParam param= OKHttpParam.builder(false);
        param.remove("platform");
        param.put("merrage",state.getId());
        OKHttp.post(HttpConfig.API_UPDATE_USER_FIELD, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                mUser.setMerrage(state.getId());
                MySelfInfo.getInstance().updateCacheString(UserInfoEdit.this, Constants.USER_MARRIAGE, state.getId());
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_LOVE, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });

    }

    @Override
    protected void onPermission(int requestCode) {
        editAvatar();
    }

    /**
     * 编辑头像
     */
    private void editAvatar(){
        if(mUser==null){
            return;
        }
        if(photoMenus==null){
            photoMenus=new PhotoOptionMenus(this);
            photoMenus.getWindow().getAttributes().width=mScreenWidth;
        }
        photoMenus.show(true);
    }

    /**
     * 上传头像
     */
    public void uploadAvatar(String path){
        KKYUtil.log(TAG,"新头像图片路径:"+path);
        if(loadingBox.getVisibility()==View.GONE) {
            loadingBox.setVisibility(View.VISIBLE);
            uploadAni.start();
        }
        uploader.uploadCover(path);
    }

    @Override
    public void onUploadProcess(int percent) {
        //uploadPro.setText(percent+ "%");
    }

    @Override
    public void onUploadResult(int code, UploadResultInfo resultInfo) {
        if (0 == code) {
            KKYUtil.log("图片上传成功："+resultInfo.getKey());
            updateHeader(resultInfo.getKey(),resultInfo.getUrl());
        } else {
            KKYUtil.log("图片上传失败："+code);
            mainView.showTopMsg(getString(R.string.ui_upload_failed)+":"+code+"");
            if (loadingBox.getVisibility() == View.VISIBLE) {
                loadingBox.setVisibility(View.GONE);
                uploadAni.stop();
            }
        }
    }

    @Override
    public void onUploadResult(int code, String key) {

    }

    /**
     * 提交更新头像
     */
    private void updateHeader(String key,final String url){
        OKHttpParam param=OKHttpParam.builder(false);
        param.remove("platform");
        param.put("avatar", key);
        OKHttp.post(HttpConfig.API_UPDATE_USER_FIELD, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m = (OKHttpResponseModel) model;
                KKYUtil.log("提交头像成功：" + m.getResponseStr());
                if (loadingBox.getVisibility() == View.VISIBLE) {
                    loadingBox.setVisibility(View.GONE);
                    uploadAni.stop();
                }
                mUser.setAvatar(url);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_HEAD, mUser));
                MySelfInfo.getInstance().updateCacheString(UserInfoEdit.this, Constants.USER_AVATAR, url);
                avatarView.setImageURI(Uri.parse(url));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }

            @Override
            public void onErr(String errMsg) {
                if (loadingBox.getVisibility() == View.VISIBLE) {
                    loadingBox.setVisibility(View.GONE);
                    uploadAni.stop();
                }
                mainView.showTopMsg(errMsg);
            }
        });
    }

    public void showDatePicker(){
        if(pwTime==null) {
            pwTime = new DatePicker(this, TimePopupWindow.Type.YEAR_MONTH_DAY);
            pwTime.getWindow().getAttributes().width=mScreenWidth;
            int end=Calendar.getInstance().get(Calendar.YEAR);
            pwTime.setRange(end-100,end);
            pwTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date) {
                    birthTv.setText(KKYUtil.dateFormatYMD(date));
                    updateBirth(KKYUtil.dateFormatYMD(date));

                }
            });
        }
        pwTime.show(new Date());
    }

    /**
     * 地区选择
     */
    public void showZonePop(){
        if(popupWindowAddress==null){
            popupWindowAddress=new OptionsPopupWindow(this);
            popupWindowAddress.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    WheelItem prov = provinceItems.get(options1);
                    WheelItem city = cityItems.get(options1).get(option2);
                    addrTv.setText(prov.getTitle().equals(city.getTitle()) ? prov.getTitle() : prov.getTitle() + " " + city.getTitle());
                    updateAddress(addrTv.getText().toString());
                }
            });
            String [] province=getResources().getStringArray(R.array.province_item);
            String  [] cities=new String[0];
            for (int i=0;i<province.length;i++){
                provinceItems.add(new WheelItem(i+"",province[i]));
                ArrayList<WheelItem> cityList=new ArrayList<WheelItem>();
                cities=getResources().getStringArray(Config.ARRAY_CITY[i]);
                for (int j=0;j<cities.length;j++){
                    cityList.add(new WheelItem(j+"",cities[j]));
                }
                cityItems.add(cityList);
            }
            popupWindowAddress.setPicker(provinceItems,cityItems,true);
            popupWindowAddress.setSelectOptions(0,0);
        }
        popupWindowAddress.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }


    /***
     * 修改生日
     */
    public void updateBirth(final String birth){
        findViewById(R.id.birth_link).setClickable(false);
        OKHttpParam param=OKHttpParam.builder(false);
        param.remove("platform");
        param.put("birthday", birth);
        OKHttp.post(HttpConfig.API_UPDATE_USER_FIELD, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                findViewById(R.id.birth_link).setClickable(true);
                KKYUtil.log(TAG, "提交保存生日成功");
                mUser.setBirthday(birth);
                birthTv.setText(birth);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_BIRTH, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }

            @Override
            public void onErr(String errMsg) {
                findViewById(R.id.birth_link).setClickable(true);
                mainView.showTopMsg(errMsg);
            }

        });
    }

    /***
     * 修改地区
     */
    public void updateAddress(final String address){
        findViewById(R.id.address_link).setClickable(false);
        OKHttpParam param=OKHttpParam.builder(false);
        param.remove("platform");
        param.put("address", address);
        OKHttp.post(HttpConfig.API_UPDATE_USER_FIELD, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                findViewById(R.id.address_link).setClickable(true);
                KKYUtil.log(TAG, "提交保存地址结果");
                mUser.setAddress(address);
                addrTv.setText(address);
                MySelfInfo.getInstance().updateCacheString(UserInfoEdit.this, Constants.USER_ADDRESS, address);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_ADDRESS, mUser));
                //alert("地址修改成功");
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }

            @Override
            public void onErr(String errMsg) {
                findViewById(R.id.address_link).setClickable(true);
                mainView.showTopMsg(errMsg);
            }

        });
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE_EDIT_NICK){
            if(resultCode==RESULT_OK){//编辑昵称成功
                String nick=data.getStringExtra(UserInfoNickEdit.RESULT_PARAM_USER_NICK);
                mUser.setNickname(nick);
                nameTv.setText(nick);
                MySelfInfo.getInstance().updateCacheString(UserInfoEdit.this, Constants.USER_NICK, nick);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_NICK, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }else{

            }
        }else if(requestCode==REQUEST_CODE_EDIT_INTRO){
            if(resultCode==RESULT_OK){//修改签名成功
                String intro=data.getStringExtra(UserInfoIntroEdit.RESULT_PARAM_INTRO);
                mUser.setIntro(intro);
                introTv.setText(intro);
                MySelfInfo.getInstance().updateCacheString(UserInfoEdit.this, Constants.USER_SIGN, intro);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_INTRO, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }else{

            }
        }else if(requestCode==REQUEST_CODE_EDIT_JOB){
            if(resultCode==RESULT_OK){//修改职业成功
                String job=data.getStringExtra(UserInfoJobEdit.RESULT_PARAM_USER_JOB);
                mUser.setJob(job);
                jobView.setText(job);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_JOB, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }else{

            }
        }else if(requestCode==REQUEST_CODE_EDIT_LOCATION){
            if(resultCode==RESULT_OK){
                String lc=data.getStringExtra(UserInfoEditLocation.RESULT_PARAM_USER_LC);
                mUser.setAddress(lc);
                addrTv.setText(lc);
                EventBus.getDefault().post(new UserEditEvent(UserEditEvent.UPDATE_ADDRESS, mUser));
                mainView.showTopMsg(getString(R.string.ui_edit_success));
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_PHOTO_CROP_CODE){//取到用于剪切的图片
            if(resultCode== Activity.RESULT_OK){
                if(data.getData()!=null){
                    UCrop uCrop = UCrop.of(data.getData(), Uri.fromFile(new File(getCacheDir(), MySelfInfo.getInstance().getId()+"avatar.png")));
                    uCrop.start(this,PhotoOptionMenus.REQUEST_CROP_CODE);
                }
            }else{
                localAvatar=null;
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_CAPTURE_CROP_CODE){//拍到用于剪切的图片
            if(resultCode== Activity.RESULT_OK){
                UCrop uCrop = UCrop.of(photoMenus.getTempUri(), Uri.fromFile(new File(getCacheDir(), MySelfInfo.getInstance().getId()+"avatar.png")));
                uCrop.start(this, PhotoOptionMenus.REQUEST_CROP_CODE);
            }else{
                localAvatar=null;
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_CROP_CODE){
            if(resultCode== Activity.RESULT_OK){
                if(data!=null){
                    Intent preview=new Intent(this, PicturePreview.class);
                    preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.UPLOAD);
                    localAvatar = UCrop.getOutput(data);
                    preview.setData(localAvatar);
                    startActivityForResult(preview, PhotoOptionMenus.REQUEST_PREVIEW_CODE);
                }else{
                    localAvatar=null;
                }
            }
        }else if(requestCode==PhotoOptionMenus.REQUEST_PREVIEW_CODE){
            if(resultCode== Activity.RESULT_OK){
                if(localAvatar!=null){
                    uploadAvatar(FileManager.getFilePath(this,localAvatar));
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
